<template>
  <div class="store-detail bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 面包屑导航 -->
    <div class="container mx-auto px-4 py-4">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/shop' }"
          >文创商城</el-breadcrumb-item
        >
        <el-breadcrumb-item>{{ store.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 店铺头部信息 -->
    <div class="store-header bg-white dark:bg-gray-800 shadow-sm">
      <div class="container mx-auto px-4">
        <!-- 店铺基本信息 -->
        <div class="py-6 flex items-center justify-between">
          <div class="flex items-center gap-6">
            <div class="relative">
              <el-avatar :size="80" :src="store.avatar" class="shadow-md" />
            </div>
            <div>
              <h1
                class="text-2xl font-bold text-gray-900 dark:text-gray-100 mb-2 flex items-center gap-3"
              >
                {{ store.name }}
                <el-tag
                  v-if="store.isOfficial"
                  type="warning"
                  effect="plain"
                  class="ml-2"
                  >官方店铺</el-tag
                >
                <el-tag v-if="store.isVerified" type="success" effect="plain"
                  >已认证</el-tag
                >
              </h1>
              <div
                class="flex items-center gap-6 text-sm text-gray-500 dark:text-gray-400"
              >
                <div class="flex items-center gap-2">
                  <el-icon><ShoppingBag /></el-icon>
                  <span>商品 {{ store.productCount }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <el-icon><Star /></el-icon>
                  <span>关注 {{ store.followers }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <el-icon><GoodsFilled /></el-icon>
                  <span>好评率 {{ store.positiveRate }}%</span>
                </div>
                <div class="flex items-center gap-2">
                  <el-icon><Timer /></el-icon>
                  <span>营业时间 {{ store.businessHours }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <el-icon><Trophy /></el-icon>
                  <span>店铺等级 {{ store.level }}</span>
                </div>
              </div>
            </div>
          </div>
          <div class="flex items-center gap-4">
            <el-button
              type="primary"
              :plain="!store.isFollowed"
              @click="handleFollowStore"
              :loading="followLoading"
              size="large"
              class="min-w-[120px]"
            >
              {{ store.isFollowed ? "已关注" : "+ 关注店铺" }}
            </el-button>
            <el-button type="success" size="large" @click="handleContact">
              <el-icon class="mr-1"><Service /></el-icon>
              联系客服
            </el-button>
          </div>
        </div>

        <!-- 导航栏 -->
        <div class="store-nav border-t dark:border-gray-700">
          <el-menu
            :default-active="activeTab"
            mode="horizontal"
            @select="handleTabChange"
            class="border-0 dark:bg-gray-800"
          >
            <el-menu-item index="all">全部商品</el-menu-item>
            <el-menu-item index="new">新品上架</el-menu-item>
            <el-menu-item index="hot">热销商品</el-menu-item>
            <el-menu-item index="promotion">优惠活动</el-menu-item>
            <el-menu-item index="category">商品分类</el-menu-item>
          </el-menu>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="container mx-auto px-4 py-6">
      <div class="flex gap-6">
        <!-- 左侧信息栏 -->
        <div class="w-[300px] flex-shrink-0 space-y-6">
          <!-- 店铺公告 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><Bell /></el-icon>
              店铺公告
            </h3>
            <div class="text-gray-600 dark:text-gray-300 text-sm">
              {{ store.announcement }}
            </div>
          </div>

          <!-- 店铺信息 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><InfoFilled /></el-icon>
              店铺信息
            </h3>
            <div class="space-y-3 text-sm">
              <div
                class="flex items-start gap-2 text-gray-600 dark:text-gray-300"
              >
                <el-icon class="mt-1"><Location /></el-icon>
                <div>
                  <div class="font-medium mb-1">店铺地址</div>
                  <div>{{ store.address }}</div>
                </div>
              </div>
              <div
                class="flex items-start gap-2 text-gray-600 dark:text-gray-300"
              >
                <el-icon class="mt-1"><Phone /></el-icon>
                <div>
                  <div class="font-medium mb-1">联系电话</div>
                  <div>{{ store.phone }}</div>
                </div>
              </div>
              <div
                class="flex items-start gap-2 text-gray-600 dark:text-gray-300"
              >
                <el-icon class="mt-1"><Timer /></el-icon>
                <div>
                  <div class="font-medium mb-1">营业时间</div>
                  <div>{{ store.businessHours }}</div>
                </div>
              </div>
              <div
                class="flex items-start gap-2 text-gray-600 dark:text-gray-300"
              >
                <el-icon class="mt-1"><Calendar /></el-icon>
                <div>
                  <div class="font-medium mb-1">开店时间</div>
                  <div>{{ store.establishedAt }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 店铺资质 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><Medal /></el-icon>
              店铺资质
            </h3>
            <div class="space-y-2 text-sm">
              <div
                class="flex items-center justify-between text-gray-600 dark:text-gray-300"
              >
                <span>营业执照</span>
                <el-button link type="primary" @click="showLicense"
                  >查看</el-button
                >
              </div>
              <div
                class="flex items-center justify-between text-gray-600 dark:text-gray-300"
              >
                <span>食品经营许可证</span>
                <el-button link type="primary" @click="showPermit"
                  >查看</el-button
                >
              </div>
              <div
                class="flex items-center justify-between text-gray-600 dark:text-gray-300"
              >
                <span>商家认证</span>
                <el-tag size="small" type="success" v-if="store.isVerified"
                  >已认证</el-tag
                >
                <el-tag size="small" type="info" v-else>未认证</el-tag>
              </div>
            </div>
          </div>

          <!-- 店铺动态 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm">
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><TrendCharts /></el-icon>
              店铺动态
            </h3>
            <div class="space-y-3 text-sm">
              <div
                v-for="(activity, index) in store.recentActivities"
                :key="index"
                class="flex items-start gap-2 text-gray-600 dark:text-gray-300 pb-2 border-b dark:border-gray-700 last:border-0"
              >
                <el-icon class="mt-1"><CircleCheck /></el-icon>
                <div>
                  <div class="mb-1">{{ activity.content }}</div>
                  <div class="text-xs text-gray-400">{{ activity.time }}</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧商品列表 -->
        <div class="flex-1">
          <!-- 筛选栏 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg p-4 shadow-sm mb-6">
            <!-- 搜索和排序 -->
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-6">
                <el-input
                  v-model="searchKeyword"
                  placeholder="搜索店内商品"
                  class="w-[300px]"
                  @input="handleSearch"
                >
                  <template #prefix>
                    <el-icon><Search /></el-icon>
                  </template>
                </el-input>
                <el-select v-model="sortBy" placeholder="排序方式" @change="handleSortChange">
                  <el-option label="综合排序" value="comprehensive" />
                  <el-option label="销量优先" value="sales" />
                  <el-option label="价格从低到高" value="priceAsc" />
                  <el-option label="价格从高到低" value="priceDesc" />
                  <el-option label="好评优先" value="rating" />
                  <el-option label="最新上架" value="newest" />
                </el-select>
                <el-select
                  v-model="selectedCategory"
                  placeholder="商品分类"
                  clearable
                  @change="handleCategoryChange"
                >
                  <el-option
                    v-for="category in store.categories"
                    :key="category.id"
                    :label="category.name"
                    :value="category.id"
                  />
                </el-select>
              </div>
              <div class="flex items-center gap-4">
                <el-switch v-model="onlyInStock" active-text="仅看有货" @change="handleFilterChange" />
                <el-switch v-model="onlyDiscount" active-text="优惠商品" @change="handleFilterChange" />
              </div>
            </div>

            <!-- 标签筛选 -->
            <div class="flex flex-wrap gap-2 mt-4">
              <el-tag
                v-for="tag in filterTags"
                :key="tag.id"
                :type="selectedTags.includes(tag.id) ? 'primary' : ''"
                class="cursor-pointer"
                @click="toggleTag(tag.id)"
              >
                {{ tag.name }}
              </el-tag>
            </div>
          </div>

          <!-- 商品列表 -->
          <div class="grid grid-cols-4 gap-6">
            <div
              v-for="product in filteredProducts"
              :key="product.id"
              class="bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden group cursor-pointer hover:shadow-md transition-shadow"
              @click="goToProduct(product.id)"
            >
              <div class="aspect-square overflow-hidden relative">
                <el-image
                  :src="product.coverImage"
                  class="w-full h-full object-cover transition-transform group-hover:scale-110"
                  fit="cover"
                />
                <div
                  v-if="product.isNew"
                  class="absolute top-2 left-2 bg-red-500 text-white text-xs px-2 py-1 rounded"
                >
                  新品
                </div>
                <div
                  v-if="product.discount"
                  class="absolute top-2 right-2 bg-primary-500 text-white text-xs px-2 py-1 rounded"
                >
                  {{ product.discount }}折
                </div>
              </div>
              <div class="p-4">
                <h3
                  class="text-gray-900 dark:text-gray-100 font-medium mb-2 line-clamp-2 group-hover:text-primary-500"
                >
                  {{ product.name }}
                </h3>
                <div class="flex items-baseline gap-2">
                  <span class="text-lg font-bold text-red-600 dark:text-red-400"
                    >¥{{ product.price }}</span
                  >
                  <span class="text-sm text-gray-400 line-through"
                    >¥{{ product.originalPrice }}</span
                  >
                </div>
                <div
                  class="mt-2 flex items-center justify-between text-sm text-gray-500 dark:text-gray-400"
                >
                  <div class="flex items-center gap-1">
                    <el-rate
                      v-model="product.rating"
                      disabled
                      :max="5"
                      :colors="['#ffd21e', '#ffd21e', '#ffd21e']"
                      :size="12"
                    />
                    <span class="ml-1">{{ product.rating }}</span>
                  </div>
                  <span>月销 {{ product.monthlySales }}</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 分页 -->
          <div class="flex justify-center mt-8">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="totalItems"
              :page-sizes="[20, 40, 60, 80]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧悬浮工具栏 -->
    <div class="fixed right-6 bottom-48 flex flex-col gap-4 items-end">
      <el-tooltip
        content="购物车"
        placement="left"
        effect="dark"
        class="toolbar-tooltip"
      >
        <el-button
          circle
          size="large"
          type="primary"
          class="w-16 h-16 flex items-center justify-center shadow-lg hover:scale-110 transition-transform"
          @click="showCart = true"
        >
          <el-badge
            v-if="cartItemCount"
            :value="cartItemCount"
            class="cart-badge"
          >
            <el-icon class="text-2xl"><ShoppingCart /></el-icon>
          </el-badge>
          <el-icon v-else class="text-2xl"><ShoppingCart /></el-icon>
        </el-button>
      </el-tooltip>

      <el-tooltip
        content="我的收藏"
        placement="left"
        effect="dark"
        class="toolbar-tooltip"
      >
        <el-button
          circle
          size="large"
          type="primary"
          class="w-16 h-16 flex items-center justify-center shadow-lg hover:scale-110 transition-transform"
          @click="showFavorites = true"
        >
          <el-badge
            v-if="favoriteCount"
            :value="favoriteCount"
            class="favorite-badge"
          >
            <el-icon class="text-2xl"><Star /></el-icon>
          </el-badge>
          <el-icon v-else class="text-2xl"><Star /></el-icon>
        </el-button>
      </el-tooltip>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="showCart"
      title="购物车"
      size="400px"
      :with-header="false"
    >
      <div class="cart-drawer h-full flex flex-col">
        <div
          class="drawer-header flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700"
        >
          <h3 class="text-lg font-medium text-gray-900 dark:text-white">
            购物车
          </h3>
          <el-button
            v-if="cartItems.length"
            type="danger"
            text
            :icon="Delete"
            @click="handleClearCart"
          >
            清空
          </el-button>
        </div>

        <!-- 购物车列表 -->
        <div
          v-if="cartItems.length"
          class="cart-items flex-1 overflow-y-auto p-4"
        >
          <div
            v-for="item in cartItems"
            :key="item.id"
            class="cart-item bg-white dark:bg-gray-800 rounded-lg shadow-sm overflow-hidden mb-4 transition-all duration-300 hover:shadow-md"
          >
            <div class="flex p-4 gap-4">
              <div
                class="item-image w-24 h-24 rounded-lg overflow-hidden flex-shrink-0"
              >
                <el-image
                  :src="item.image"
                  :alt="item.title"
                  class="w-full h-full object-cover"
                  fit="cover"
                />
              </div>
              <div class="item-info flex-1 min-w-0">
                <div
                  class="item-name text-gray-900 dark:text-white font-medium mb-2 line-clamp-2 hover:text-primary-600 transition-colors"
                >
                  {{ item.title }}
                </div>
                <div class="item-price flex items-center justify-between">
                  <span
                    class="price text-primary-600 dark:text-primary-400 font-semibold"
                  >
                    ¥{{ formatPrice(item.price) }}
                  </span>
                  <el-input-number
                    v-model="item.quantity"
                    :min="1"
                    :max="item.stock || 99"
                    size="small"
                    @change="handleQuantityChange(item)"
                  />
                </div>
              </div>
              <el-button
                class="remove-button text-gray-400 hover:text-red-500 transition-colors"
                type="text"
                :icon="Close"
                @click="handleRemoveFromCart(item)"
              />
            </div>
          </div>
        </div>

        <!-- 空购物车状态 -->
        <el-empty v-else description="暂无购物商品">
          <el-button type="primary" @click="showCart = false">
            去逛逛
          </el-button>
        </el-empty>

        <!-- 购物车底部 -->
        <div
          v-if="cartItems.length"
          class="cart-footer bg-white dark:bg-gray-800 border-t border-gray-200 dark:border-gray-700 p-4"
        >
          <div class="total-price flex items-center justify-between mb-4">
            <span class="label text-gray-600 dark:text-gray-400">合计:</span>
            <span
              class="amount text-xl font-bold text-primary-600 dark:text-primary-400"
            >
              ¥{{ formatPrice(totalPrice) }}
            </span>
          </div>
          <el-button
            type="primary"
            class="checkout-button w-full h-12 text-lg font-medium"
            :loading="checkoutLoading"
            @click="handleCheckout"
          >
            结算 ({{ cartItemCount }}件)
          </el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 收藏夹抽屉 -->
    <el-drawer v-model="showFavorites" title="我的收藏" size="400px">
      <div class="favorites-drawer">
        <div v-if="favoriteItems.length" class="favorite-items">
          <div
            v-for="item in favoriteItems"
            :key="item.id"
            class="favorite-item"
          >
            <div class="item-image">
              <el-image :src="item.image" :alt="item.title" fit="cover" />
            </div>
            <div class="item-info">
              <div class="item-name">{{ item.title }}</div>
              <div class="item-price">¥{{ formatPrice(item.price) }}</div>
            </div>
            <div class="item-actions">
              <el-button
                type="primary"
                size="small"
                @click="handleAddToCart(item)"
              >
                加入购物车
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleRemoveFavorite(item)"
              >
                取消收藏
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无收藏商品">
          <el-button type="primary" @click="showFavorites = false">
            去逛逛
          </el-button>
        </el-empty>
      </div>
    </el-drawer>

    <!-- 客服对话框 -->
    <el-dialog
      v-model="showServiceDialog"
      title="联系客服"
      width="480px"
      :close-on-click-modal="false"
      class="service-dialog"
    >
      <div class="p-6">
        <!-- 客服信息 -->
        <div
          class="flex items-center gap-6 mb-6 pb-6 border-b dark:border-gray-700"
        >
          <el-avatar :size="64" :src="store.serviceAvatar" class="shadow-md" />
          <div>
            <h3
              class="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2 flex items-center gap-2"
            >
              {{ store.serviceName }}
              <el-tag size="small" type="success">在线</el-tag>
            </h3>
            <div class="text-sm text-gray-500 dark:text-gray-400">
              <div class="flex items-center gap-4">
                <span class="flex items-center gap-1">
                  <el-icon><Timer /></el-icon>
                  工作时间: {{ store.businessHours }}
                </span>
                <span class="flex items-center gap-1">
                  <el-icon><ChatDotRound /></el-icon>
                  平均响应: 2分钟
                </span>
              </div>
            </div>
          </div>
        </div>

        <!-- 联系方式 -->
        <div class="space-y-4">
          <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
            <h4
              class="font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><ChatDotRound /></el-icon>
              在线咨询
            </h4>
            <div class="text-sm text-gray-600 dark:text-gray-300 mb-4">
              在线客服会第一时间为您解答问题，提供专业的购物咨询服务。
            </div>
            <el-button type="primary" block @click="startChat">
              <el-icon class="mr-2"><Message /></el-icon>
              开始在线咨询
            </el-button>
          </div>

          <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
            <h4
              class="font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><Phone /></el-icon>
              电话咨询
            </h4>
            <div class="text-sm text-gray-600 dark:text-gray-300 mb-4">
              如需紧急联系，可以直接拨打店铺客服电话。
            </div>
            <el-button type="success" block @click="callService">
              <el-icon class="mr-2"><Phone /></el-icon>
              {{ store.phone }}
            </el-button>
          </div>

          <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
            <h4
              class="font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center gap-2"
            >
              <el-icon><QuestionFilled /></el-icon>
              常见问题
            </h4>
            <div class="space-y-2">
              <div
                v-for="(faq, index) in commonQuestions"
                :key="index"
                class="text-sm text-gray-600 dark:text-gray-300 cursor-pointer hover:text-primary-500 dark:hover:text-primary-400"
                @click="handleFaqClick(faq)"
              >
                {{ faq.question }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 在线聊天对话框 -->
    <el-dialog
      v-model="showChatDialog"
      title="在线咨询"
      width="900px"
      :close-on-click-modal="false"
      class="chat-dialog"
      :fullscreen="isMobile"
      @close="handleChatClose"
      destroy-on-close
    >
      <div class="flex h-[650px]">
        <!-- 左侧聊天区域 -->
        <div class="flex-1 flex flex-col bg-gray-50 dark:bg-gray-800">
          <!-- 聊天头部 -->
          <div
            class="p-4 bg-white dark:bg-gray-800 border-b dark:border-gray-700 flex items-center justify-between shadow-sm"
          >
            <div class="flex items-center gap-3">
              <div class="relative">
                <el-avatar
                  :size="40"
                  :src="store.serviceAvatar"
                  class="shadow-sm"
                />
                <div
                  class="absolute -bottom-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white dark:border-gray-800"
                ></div>
              </div>
              <div>
                <div class="font-medium text-gray-900 dark:text-gray-100">
                  {{ store.serviceName }}
                </div>
                <div
                  class="text-xs text-gray-500 dark:text-gray-400 flex items-center gap-2"
                >
                  <span class="flex items-center gap-1">
                    <div class="w-1.5 h-1.5 bg-green-500 rounded-full"></div>
                    在线
                  </span>
                  <span>|</span>
                  <span>平均响应: 2分钟</span>
                </div>
              </div>
            </div>
            <div class="flex items-center gap-2">
              <el-tooltip content="清空聊天记录" placement="top">
                <el-button
                  type="danger"
                  :icon="Delete"
                  circle
                  plain
                  size="small"
                  @click="clearChat"
                />
              </el-tooltip>
              <el-tooltip content="查看历史消息" placement="top">
                <el-button
                  type="primary"
                  :icon="More"
                  circle
                  plain
                  size="small"
                  @click="viewHistory"
                />
              </el-tooltip>
            </div>
          </div>

          <!-- 聊天消息区域 -->
          <div class="flex-1 overflow-y-auto p-4 space-y-4" ref="chatContainer">
            <!-- 系统消息 -->
            <div v-if="chatMessages.length === 0" class="flex justify-center">
              <div
                class="bg-gray-100 dark:bg-gray-700 rounded-lg px-4 py-2 text-sm text-gray-500 dark:text-gray-400"
              >
                暂无聊天记录
              </div>
            </div>
            <!-- 消息列表 -->
            <div
              v-for="(message, index) in chatMessages"
              :key="index"
              :class="[
                'flex',
                message.type === 'received' ? 'justify-start' : 'justify-end',
              ]"
            >
              <div
                class="flex items-start gap-2 max-w-[70%] group"
                :class="[
                  message.type === 'received' ? 'flex-row' : 'flex-row-reverse',
                ]"
              >
                <el-avatar
                  :size="36"
                  :src="
                    message.type === 'received'
                      ? store.serviceAvatar
                      : userAvatar
                  "
                  class="flex-shrink-0"
                />
                <div
                  class="flex flex-col"
                  :class="[
                    message.type === 'received' ? 'items-start' : 'items-end',
                  ]"
                >
                  <div class="text-xs text-gray-500 dark:text-gray-400 mb-1">
                    {{ message.time }}
                  </div>
                  <div
                    class="relative message-bubble"
                    :class="[
                      message.type === 'received'
                        ? 'bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100'
                        : 'bg-primary-500 text-white',
                      message.type === 'received'
                        ? 'message-received'
                        : 'message-sent',
                    ]"
                  >
                    <!-- 文本消息 -->
                    <template v-if="message.contentType === 'text'">
                      <div class="whitespace-pre-wrap break-words">
                        {{ message.content }}
                      </div>
                    </template>
                    <!-- 图片消息 -->
                    <template v-else-if="message.contentType === 'image'">
                      <el-image
                        :src="message.content"
                        :preview-src-list="[message.content]"
                        class="max-w-[300px] rounded cursor-zoom-in"
                        fit="cover"
                      />
                    </template>
                    <!-- 商品卡片 -->
                    <template v-else-if="message.contentType === 'product'">
                      <div
                        class="bg-gray-50 dark:bg-gray-800 rounded p-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-600"
                        @click="goToProduct(message.content.id)"
                      >
                        <div class="flex gap-2">
                          <el-image
                            :src="message.content.coverImage"
                            class="w-16 h-16 rounded"
                          />
                          <div class="flex-1 min-w-0">
                            <div class="text-sm font-medium truncate">
                              {{ message.content.name }}
                            </div>
                            <div class="text-primary-500 text-sm mt-1">
                              ¥{{ message.content.price }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </template>
                  </div>
                  <!-- 消息操作 -->
                  <div
                    class="message-actions opacity-0 group-hover:opacity-100 transition-opacity mt-1 flex items-center gap-2"
                    :class="[
                      message.type === 'received'
                        ? 'justify-start'
                        : 'justify-end',
                    ]"
                  >
                    <el-button text size="small" @click="copyMessage(message)"
                      >复制</el-button
                    >
                    <el-button
                      v-if="message.type === 'sent'"
                      text
                      size="small"
                      type="danger"
                      @click="deleteMessage(index)"
                      >删除</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
            <!-- 对方正在输入提示 -->
            <div
              v-if="isTyping"
              class="flex items-center gap-2 text-gray-500 dark:text-gray-400"
            >
              <el-avatar :size="36" :src="store.serviceAvatar" />
              <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>

          <!-- 工具栏 -->
          <div
            class="bg-white dark:bg-gray-800 border-t dark:border-gray-700 p-2"
          >
            <div class="flex items-center gap-2">
              <el-tooltip content="表情" placement="top">
                <el-popover placement="top" :width="300" trigger="click">
                  <template #reference>
                    <el-button :icon="ChatRound" circle plain />
                  </template>
                  <div class="grid grid-cols-8 gap-2 p-2">
                    <div
                      v-for="emoji in emojis"
                      :key="emoji"
                      class="w-8 h-8 flex items-center justify-center text-lg cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 rounded"
                      @click="insertEmoji(emoji)"
                    >
                      {{ emoji }}
                    </div>
                  </div>
                </el-popover>
              </el-tooltip>
              <el-tooltip content="发送图片" placement="top">
                <el-upload
                  class="upload-demo"
                  action="/api/upload"
                  :show-file-list="false"
                  :before-upload="beforeUpload"
                  :on-success="handleUploadSuccess"
                >
                  <el-button :icon="Picture" circle plain />
                </el-upload>
              </el-tooltip>
              <el-tooltip content="截图" placement="top">
                <el-button
                  :icon="Camera"
                  circle
                  plain
                  @click="takeScreenshot"
                />
              </el-tooltip>
              <el-divider direction="vertical" />
              <el-button size="small" @click="sendQuickReply('查询物流')"
                >查询物流</el-button
              >
              <el-button size="small" @click="sendQuickReply('申请退款')"
                >申请退款</el-button
              >
              <el-button size="small" @click="sendQuickReply('修改地址')"
                >修改地址</el-button
              >
            </div>
          </div>

          <!-- 输入区域 -->
          <div
            class="bg-white dark:bg-gray-800 p-4 border-t dark:border-gray-700"
          >
            <div class="flex gap-2">
              <el-input
                v-model="messageInput"
                type="textarea"
                :rows="3"
                placeholder="请输入消息..."
                resize="none"
                @keydown.enter.prevent="sendMessage"
                @input="handleInput"
              />
              <el-button
                type="primary"
                class="flex-shrink-0"
                :loading="sendLoading"
                @click="sendMessage"
                :disabled="!messageInput.trim()"
              >
                发送
                <template #icon>
                  <el-icon class="ml-1"><Position /></el-icon>
                </template>
              </el-button>
            </div>
            <div class="mt-2 flex justify-between items-center">
              <div class="text-xs text-gray-400">
                按 Enter 发送消息，Shift + Enter 换行
              </div>
              <div class="text-xs text-gray-400">
                {{ messageInput.length }}/500
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧信息栏 -->
        <div
          class="w-[280px] border-l dark:border-gray-700 bg-white dark:bg-gray-800 overflow-y-auto"
        >
          <!-- 最近咨询商品 -->
          <div class="p-4 border-b dark:border-gray-700">
            <h4
              class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3 flex items-center justify-between"
            >
              <span>最近咨询商品</span>
              <el-button type="primary" link size="small">查看更多</el-button>
            </h4>
            <div class="space-y-3">
              <div
                v-for="product in recentProducts"
                :key="product.id"
                class="flex items-center gap-2 p-2 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer transition-colors"
                @click="sendProductLink(product)"
              >
                <el-image
                  :src="product.coverImage"
                  class="w-16 h-16 rounded object-cover"
                />
                <div class="flex-1 min-w-0">
                  <div
                    class="text-sm text-gray-900 dark:text-gray-100 line-clamp-2"
                  >
                    {{ product.name }}
                  </div>
                  <div class="text-sm text-primary-500 mt-1">
                    ¥{{ product.price }}
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 常见问题 -->
          <div class="p-4">
            <h4
              class="text-sm font-medium text-gray-900 dark:text-gray-100 mb-3"
            >
              常见问题
            </h4>
            <div class="space-y-2">
              <div
                v-for="(faq, index) in commonQuestions"
                :key="index"
                class="p-2 text-sm text-gray-600 dark:text-gray-300 cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700 rounded-lg transition-colors"
                @click="sendQuickReply(faq.question)"
              >
                {{ faq.question }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 历史消息抽屉 -->
    <el-drawer
      v-model="showHistory"
      title="历史消息"
      direction="rtl"
      size="500px"
    >
      <div class="p-4">
        <el-timeline>
          <el-timeline-item
            v-for="(history, index) in chatHistory"
            :key="index"
            :timestamp="history.date"
            placement="top"
          >
            <div class="bg-gray-50 dark:bg-gray-800 rounded-lg p-4">
              <div class="text-sm text-gray-900 dark:text-gray-100 mb-2">
                {{ history.title }}
              </div>
              <div class="text-xs text-gray-500">
                {{ history.messages }} 条消息
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-drawer>

    <!-- 营业执照查看弹窗 -->
    <el-dialog v-model="showLicenseDialog" title="营业执照" width="600px">
      <el-image :src="store.license" class="w-full" />
    </el-dialog>

    <!-- 许可证查看弹窗 -->
    <el-dialog v-model="showPermitDialog" title="食品经营许可证" width="600px">
      <el-image :src="store.permit" class="w-full" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, nextTick, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ShoppingBag,
  Star,
  GoodsFilled,
  Timer,
  Service,
  Bell,
  InfoFilled,
  Location,
  Phone,
  Medal,
  Search,
  ChatDotRound,
  Calendar,
  Trophy,
  TrendCharts,
  CircleCheck,
  Message,
  QuestionFilled,
  Delete,
  More,
  Picture,
  Camera,
  Position,
  ChatRound,
  ShoppingCart,
  Close,
} from "@element-plus/icons-vue";
import service from "@/api/axios";
import { useUserStore } from "@/stores/user";

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();

// 获取店铺ID
const storeId = route.params.id;

// 店铺数据
const store = ref({
  id: storeId,
  name: "贵港特色手工艺品店",
  avatar: "/images/store/avatar.jpg",
  isOfficial: true,
  isVerified: true,
  level: "LV5",
  productCount: 128,
  followers: 1000,
  positiveRate: 98,
  isFollowed: false,
  businessHours: "09:00-21:00",
  announcement:
    "欢迎光临本店！本店主营贵港特色手工艺品，所有商品均为本地工艺人纯手工制作，品质保证。新品优惠活动进行中，欢迎选购！",
  address: "广西贵港市港北区贵港文创园区A区101号",
  phone: "0775-12345678",
  establishedAt: "2020-01-01",
  serviceAvatar: "/images/store/service.jpg",
  serviceName: "小艺",
  license: "/images/store/license.jpg",
  permit: "/images/store/permit.jpg",
  categories: [
    { id: 1, name: "手工编织" },
    { id: 2, name: "陶瓷制品" },
    { id: 3, name: "木质工艺品" },
    { id: 4, name: "特色小吃" },
  ],
  recentActivities: [
    { content: "新上架手工编织包系列", time: "2024-03-20 10:30" },
    { content: "店铺春季优惠活动开启", time: "2024-03-19 15:00" },
    { content: "新增陶瓷茶具系列商品", time: "2024-03-18 09:00" },
  ],
});

// 页面状态
const activeTab = ref("all");
const followLoading = ref(false);
const searchKeyword = ref("");
const sortBy = ref("comprehensive");
const selectedCategory = ref(null);
const onlyInStock = ref(false);
const onlyDiscount = ref(false);
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(100);
const showServiceDialog = ref(false);
const showLicenseDialog = ref(false);
const showPermitDialog = ref(false);
const selectedTags = ref([]);

// 检查用户是否已登录
const checkLogin = () => {
  if (!userStore.isLoggedIn) {
    ElMessageBox.confirm(
      '此功能需要登录后使用，是否立即登录？',
      '提示',
      {
        confirmButtonText: '去登录',
        cancelButtonText: '取消',
        type: 'info'
      }
    ).then(() => {
      // 保存当前页面路径，登录后返回
      localStorage.setItem('redirectPath', router.currentRoute.value.fullPath);
      router.push('/login');
    }).catch(() => {
      // 用户取消登录
    });
    return false;
  }
  return true;
};

// 筛选标签
const filterTags = [
  { id: 1, name: "新品" },
  { id: 2, name: "促销" },
  { id: 3, name: "包邮" },
  { id: 4, name: "有视频" },
  { id: 5, name: "限时特惠" },
];

// 商品数据
const products = ref([
  {
    id: 1,
    name: "贵港特色手工编织包",
    coverImage: "/images/products/bag1.jpg",
    price: 128,
    originalPrice: 168,
    rating: 4.8,
    monthlySales: 286,
    location: "贵港",
    inStock: true,
    isDiscount: true,
    isNew: true,
    discount: 7.5,
  },
  // ... 更多商品数据
]);

// 增加原始数据存储
const originalProducts = ref([]);

// 获取店铺数据
const fetchStoreData = async () => {
  try {
    console.log('正在获取店铺信息，ID:', storeId);
    const response = await service.get(`/public/shop/stores/${storeId}`);
    if (response && response.data) {
      console.log('API返回的店铺数据:', response.data);
      
      // 合并API返回的数据，使用测试数据中可能不存在的字段
      const apiStore = response.data;
      store.value = {
        ...store.value, // 保留默认测试数据
        ...apiStore,    // 覆盖API返回的值
      };
      
      // 确保头像有效
      if (!store.value.avatar || store.value.avatar.startsWith('/images/')) {
        store.value.avatar = "/images/store/avatar.jpg";
      }
      
      // 确保店铺已认证和是否官方的字段
      if (apiStore.isVerified === undefined) {
        store.value.isVerified = true; // 默认已认证
      }
      
      if (apiStore.isOfficial === undefined) {
        store.value.isOfficial = true; // 默认为官方店铺
      }
      
      // 关注状态使用模拟数据 - 默认未关注
      store.value.isFollowed = false;
    }
  } catch (error) {
    console.error("获取店铺数据失败:", error);
    ElMessage.error("获取店铺数据失败，请刷新重试");
    // 保留默认测试数据
  }
  
  // 获取商品分类
  await fetchCategories();
  
  // 获取店铺商品
  fetchStoreProducts();
};

// 获取店铺商品
const fetchStoreProducts = async () => {
  try {
    console.log('获取店铺商品列表，店铺ID:', storeId);
    
    // 简化API调用，不包含任何筛选参数，获取所有商品数据
    const response = await service.get(`/public/shop/stores/${storeId}/products`);
    
    if (response && response.data) {
      let productList = [];
      
      // 服务器返回了商品列表
      if (Array.isArray(response.data)) {
        // 转换API返回的字段名称以匹配组件使用的字段名
        productList = response.data.map(item => ({
          id: item.id,
          name: item.title,
          coverImage: item.image,
          price: item.price,
          originalPrice: item.price * 1.2, // 假设原价比现价高20%
          rating: item.rating || 4.5,
          monthlySales: item.sales,
          categoryId: item.categoryId,
          tags: item.tags || [],
          isNew: item.tags?.includes('新品'),
          discount: item.tags?.includes('促销') ? 8 : null,
          inStock: item.stock > 0,
          stock: item.stock,
        }));
      } else if (response.data.content && Array.isArray(response.data.content)) {
        // Spring Data 分页格式
        productList = response.data.content.map(item => ({
          id: item.id,
          name: item.title,
          coverImage: item.image,
          price: item.price,
          originalPrice: item.price * 1.2, // 假设原价比现价高20%
          rating: item.rating || 4.5,
          monthlySales: item.sales,
          categoryId: item.categoryId,
          tags: item.tags || [],
          isNew: item.tags?.includes('新品'),
          discount: item.tags?.includes('促销') ? 8 : null,
          inStock: item.stock > 0,
          stock: item.stock,
        }));
      } else {
        console.warn('后端返回的数据格式不符合预期:', response);
        // 使用测试数据
        console.info("使用本地模拟数据显示");
      }
      
      // 保存原始数据
      originalProducts.value = [...productList];
      
      // 应用前端筛选
      applyFrontendFilters();
    }
  } catch (error) {
    console.error("获取店铺商品失败:", error);
    ElMessage.error("获取商品列表失败，请刷新重试");
    // 保留默认测试数据
  }
};

// 前端筛选处理
const applyFrontendFilters = () => {
  // 从原始数据开始筛选
  let filtered = [...originalProducts.value];
  
  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(p => p.name.toLowerCase().includes(keyword));
  }
  
  // 分类筛选
  if (selectedCategory.value) {
    filtered = filtered.filter(p => p.categoryId === selectedCategory.value);
  }
  
  // 标签筛选
  if (selectedTags.value.length > 0) {
    filtered = filtered.filter(p => {
      return selectedTags.value.some(tagId => {
        const tagName = filterTags.find(t => t.id === tagId)?.name;
        return tagName && p.tags?.includes(tagName);
      });
    });
  }
  
  // 仅看有货
  if (onlyInStock.value) {
    filtered = filtered.filter(p => p.inStock);
  }
  
  // 优惠商品
  if (onlyDiscount.value) {
    filtered = filtered.filter(p => p.discount);
  }
  
  // 根据标签过滤
  if (activeTab.value === 'new') {
    filtered = filtered.filter(p => p.isNew || p.tags?.includes('新品'));
  } else if (activeTab.value === 'hot') {
    filtered = filtered.filter(p => p.monthlySales > 100 || p.tags?.includes('热销')); // 假设月销量>100的是热销商品
  } else if (activeTab.value === 'promotion') {
    filtered = filtered.filter(p => p.discount || p.tags?.includes('促销'));
  }
  
  // 排序处理
  if (sortBy.value === 'sales') {
    filtered.sort((a, b) => b.monthlySales - a.monthlySales);
  } else if (sortBy.value === 'priceAsc') {
    filtered.sort((a, b) => a.price - b.price);
  } else if (sortBy.value === 'priceDesc') {
    filtered.sort((a, b) => b.price - a.price);
  } else if (sortBy.value === 'rating') {
    filtered.sort((a, b) => b.rating - a.rating);
  } else if (sortBy.value === 'newest') {
    // 使用ID倒序排列，假设ID越大说明越新
    filtered.sort((a, b) => b.id - a.id);
  }
  
  // 更新商品列表
  products.value = filtered;
};

// 根据排序选项获取排序参数
const getSortParam = () => {
  switch (sortBy.value) {
    case 'sales':
      return 'monthlySales,desc';
    case 'priceAsc':
      return 'price,asc';
    case 'priceDesc':
      return 'price,desc';
    case 'rating':
      return 'rating,desc';
    case 'newest':
      return 'createTime,desc';
    default:
      return ''; // 综合排序
  }
};

// 计算属性：过滤后的商品列表 - 添加前端分页
const filteredProducts = computed(() => {
  // 前端分页
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  
  return products.value.slice(startIndex, endIndex);
});

// 计算总商品数（用于分页）
const totalItems = computed(() => {
  return products.value.length;
});

// 方法
const handleTabChange = (tab) => {
  activeTab.value = tab;
  // 切换标签页后重新获取商品列表
  fetchStoreProducts();
};

const handleFollowStore = async () => {
  if (!checkLogin()) return;
  
  followLoading.value = true;
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 500));
    
    // 直接修改前端状态，不调用API
    if (store.value.isFollowed) {
      ElMessage.success("已取消关注");
      store.value.followers--; // 减少粉丝数
    } else {
      ElMessage.success("关注成功");
      store.value.followers++; // 增加粉丝数
    }
    // 切换关注状态
    store.value.isFollowed = !store.value.isFollowed;
  } catch (error) {
    console.error("关注操作模拟失败:", error);
    ElMessage.error("操作失败，请重试");
  } finally {
    followLoading.value = false;
  }
};

const handleContact = () => {
  showServiceDialog.value = true;
};

// 价格格式化
const formatPrice = (price) => {
  return parseFloat(price).toFixed(2);
};

const handleSizeChange = (size) => {
  pageSize.value = size;
  // 使用前端分页，无需重新请求API
};

const handlePageChange = (page) => {
  currentPage.value = page;
  // 使用前端分页，无需重新请求API
};

const toggleTag = (tagId) => {
  const index = selectedTags.value.indexOf(tagId);
  if (index > -1) {
    selectedTags.value.splice(index, 1);
  } else {
    selectedTags.value.push(tagId);
  }
  currentPage.value = 1; // 重置分页
  applyFrontendFilters();
};

const goToProduct = (productId) => {
  router.push(`/shop/product/${productId}`);
};

const showLicense = () => {
  showLicenseDialog.value = true;
};

const showPermit = () => {
  showPermitDialog.value = true;
};

// 购物车相关
const showCart = ref(false);
const cartItems = ref([]);
const checkoutLoading = ref(false);

// 计算购物车商品数量
const cartItemCount = computed(() => {
  return cartItems.value.reduce((total, item) => total + item.quantity, 0);
});

// 计算购物车总价
const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    return total + item.price * item.quantity;
  }, 0);
});

// 收藏相关
const showFavorites = ref(false);
const favoriteItems = ref([]);
const favoriteCount = computed(() => favoriteItems.value.length);

// 获取收藏列表
const getFavoriteList = async () => {
  if (!userStore.isLoggedIn) return;
  
  try {
    const response = await service.get("/shop/favorites/list");
    if (response && response.data) {
      favoriteItems.value = response.data;
    }
  } catch (error) {
    console.error("获取收藏列表失败:", error);
    ElMessage.error("获取收藏列表失败");
  }
};

// 处理取消收藏
const handleRemoveFavorite = async (item) => {
  try {
    await service.delete(`/shop/favorites/${item.id}`);
    const index = favoriteItems.value.findIndex((i) => i.id === item.id);
    if (index > -1) {
      favoriteItems.value.splice(index, 1);
      ElMessage.success("已取消收藏");
    }
  } catch (error) {
    console.error("取消收藏失败:", error);
    ElMessage.error("取消收藏失败");
  }
};

// 处理加入购物车
const handleAddToCart = (product) => {
  if (!checkLogin()) return;
  
  try {
    // 调用添加购物车API
    service.post("/shop/cart/add", {
      productId: product.id,
      quantity: 1,
      selected: true,
    });
    
    ElMessage.success("已添加到购物车");
    
    // 如果购物车已打开，刷新购物车
    if (showCart.value) {
      fetchCartItems();
    }
  } catch (error) {
    console.error("添加到购物车失败:", error);
    ElMessage.error("添加失败，请重试");
  }
};

// 获取购物车列表
const fetchCartItems = async () => {
  if (!userStore.isLoggedIn) return;
  
  try {
    const response = await service.get("/shop/cart/list");
    if (response && response.data) {
      cartItems.value = response.data;
    }
  } catch (error) {
    console.error("获取购物车列表失败:", error);
    // 保留默认空数组
  }
};

// 处理从购物车移除
const handleRemoveFromCart = async (item) => {
  try {
    await service.delete(`/shop/cart/${item.id}`);
    const index = cartItems.value.findIndex((i) => i.id === item.id);
    if (index > -1) {
      cartItems.value.splice(index, 1);
      ElMessage.success("已从购物车移除");
    }
  } catch (error) {
    console.error("从购物车移除失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

// 处理清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm("确定要清空购物车吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    
    await service.delete("/shop/cart/clear");
    cartItems.value = [];
    ElMessage.success("购物车已清空");
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作
      return;
    }
    console.error("清空购物车失败:", error);
    ElMessage.error("清空购物车失败");
  }
};

// 处理数量变化
const handleQuantityChange = async (item) => {
  // 确保数量在有效范围内
  if (item.quantity < 1) {
    item.quantity = 1;
  }
  if (item.stock && item.quantity > item.stock) {
    item.quantity = item.stock;
    ElMessage.warning(`该商品库存只有 ${item.stock} 件`);
  }
  
  try {
    await service.put(`/shop/cart/update`, {
      id: item.id,
      quantity: item.quantity
    });
  } catch (error) {
    console.error("更新购物车数量失败:", error);
    ElMessage.error("更新数量失败");
    // 回滚数量变更
    fetchCartItems();
  }
};

// 处理结算
const handleCheckout = async () => {
  if (!cartItems.value.length) {
    ElMessage.warning("购物车是空的");
    return;
  }

  checkoutLoading.value = true;
  try {
    // 获取已选中的商品ID
    const selectedItems = cartItems.value.filter(item => item.selected);
    if (selectedItems.length === 0) {
      ElMessage.warning("请选择要结算的商品");
      checkoutLoading.value = false;
      return;
    }
    
    // 跳转到结算页
    router.push({
      path: "/order/confirm",
      query: {
        type: "cart",
        items: selectedItems.map(item => item.id).join(",")
      }
    });
  } catch (error) {
    console.error("结算失败:", error);
    ElMessage.error("结算失败，请重试");
  } finally {
    checkoutLoading.value = false;
  }
};

// 聊天相关状态
const showChatDialog = ref(false);
const messageInput = ref("");
const chatMessages = ref([]);
const chatContainer = ref(null);
const isMobile = ref(window.innerWidth <= 768);
const isTyping = ref(false);
const sendLoading = ref(false);
const showHistory = ref(false);
const userAvatar = ref("/images/avatar/default.jpg");

// 表情列表
const emojis = [
  "😊",
  "😂",
  "🤣",
  "😍",
  "😒",
  "😘",
  "🥰",
  "😅",
  "😁",
  "👍",
  "👎",
  "❤️",
  "💔",
  "🎉",
  "🎂",
  "🌹",
];

// 历史消息
const chatHistory = [
  { date: "2024-03-20", title: "咨询商品详情", messages: 12 },
  { date: "2024-03-19", title: "售后服务咨询", messages: 8 },
  { date: "2024-03-18", title: "物流查询", messages: 5 },
];

// 最近咨询商品
const recentProducts = computed(() => {
  return products.value.slice(0, 3);
});

// 发送消息
const sendMessage = async () => {
  if (!messageInput.value.trim()) return;

  sendLoading.value = true;
  try {
    const message = {
      type: "sent",
      contentType: "text",
      content: messageInput.value,
      time: new Date().toLocaleTimeString(),
    };
    chatMessages.value.push(message);
    messageInput.value = "";

    // 滚动到底部
    await nextTick();
    scrollToBottom();

    // 显示对方正在输入
    isTyping.value = true;

    // 模拟客服回复
    setTimeout(() => {
      isTyping.value = false;
      chatMessages.value.push({
        type: "received",
        contentType: "text",
        content: "您好，请问有什么可以帮您的吗？",
        time: new Date().toLocaleTimeString(),
      });
      scrollToBottom();
    }, 1500);
  } finally {
    sendLoading.value = false;
  }
};

// 滚动到底部
const scrollToBottom = () => {
  chatContainer.value?.scrollTo({
    top: chatContainer.value.scrollHeight,
    behavior: "smooth",
  });
};

// 发送商品链接
const sendProductLink = (product) => {
  chatMessages.value.push({
    type: "sent",
    contentType: "product",
    content: product,
    time: new Date().toLocaleTimeString(),
  });
  scrollToBottom();

  // 模拟客服回复
  setTimeout(() => {
    chatMessages.value.push({
      type: "received",
      contentType: "text",
      content: `您好，${product.name} 目前有货，请问您想了解哪些具体信息呢？`,
      time: new Date().toLocaleTimeString(),
    });
    scrollToBottom();
  }, 1000);
};

// 插入表情
const insertEmoji = (emoji) => {
  messageInput.value += emoji;
};

// 上传图片
const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }
  return true;
};

const handleUploadSuccess = (response) => {
  chatMessages.value.push({
    type: "sent",
    contentType: "image",
    content: response.url,
    time: new Date().toLocaleTimeString(),
  });
  scrollToBottom();
};

// 截图
const takeScreenshot = () => {
  ElMessage.info("截图功能开发中...");
};

// 复制消息
const copyMessage = (message) => {
  if (message.contentType === "text") {
    navigator.clipboard.writeText(message.content);
    ElMessage.success("复制成功");
  }
};

// 删除消息
const deleteMessage = (index) => {
  chatMessages.value.splice(index, 1);
};

// 清空聊天
const clearChat = () => {
  ElMessageBox.confirm("确定要清空所有聊天记录吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    chatMessages.value = [];
    ElMessage.success("聊天记录已清空");
  });
};

// 查看历史消息
const viewHistory = () => {
  showHistory.value = true;
};

// 输入提示
const handleInput = () => {
  if (messageInput.value.length > 500) {
    messageInput.value = messageInput.value.slice(0, 500);
  }
};

// 修改startChat方法
const startChat = () => {
  showServiceDialog.value = false;
  showChatDialog.value = true;
  // 添加欢迎消息
  chatMessages.value = [
    {
      type: "received",
      contentType: "text",
      content: "您好！欢迎光临本店，请问有什么可以帮您的吗？",
      time: new Date().toLocaleTimeString(),
    },
  ];
};

// 监听窗口大小变化
onMounted(() => {
  window.addEventListener("resize", () => {
    isMobile.value = window.innerWidth <= 768;
  });
  
  // 获取店铺数据
  fetchStoreData();
  
  // 如果已登录，获取购物车和收藏列表
  if (userStore.isLoggedIn) {
    fetchCartItems();
    getFavoriteList();
  }
});

// 聊天对话框关闭处理
const handleChatClose = () => {
  // 可以在这里保存聊天记录等操作
};

// 处理常见问题点击
const handleFaqClick = (faq) => {
  // TODO: 实现常见问题点击处理逻辑
  ElMessage.success(`正在为您解答常见问题：${faq.question}`);
};

// 发送快速回复
const sendQuickReply = (content) => {
  messageInput.value = content;
  sendMessage();
};

const callService = () => {
  // TODO: 实现电话咨询功能
  window.location.href = `tel:${store.value.phone}`;
};

const commonQuestions = ref([
  { question: "如何退货？" },
  { question: "如何申请发票？" },
  { question: "如何查询订单状态？" },
  { question: "如何修改收货地址？" },
  { question: "如何联系客服？" },
]);

// 处理搜索内容变化
const handleSearch = () => {
  currentPage.value = 1; // 重置分页
  applyFrontendFilters();
};

// 处理排序方式变化
const handleSortChange = () => {
  currentPage.value = 1; // 重置分页
  applyFrontendFilters();
};

// 处理分类变化
const handleCategoryChange = () => {
  currentPage.value = 1; // 重置分页
  applyFrontendFilters();
};

// 处理筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1; // 重置分页
  applyFrontendFilters();
};

// 获取商品分类
const fetchCategories = async () => {
  try {
    const response = await service.get(`/public/shop/categories`);
    if (response && response.data && Array.isArray(response.data)) {
      // 更新商店分类
      store.value.categories = response.data;
    }
  } catch (error) {
    console.error("获取商品分类失败:", error);
    // 使用默认分类
  }
};
</script>

<style lang="scss" scoped>
.store-nav {
  :deep(.el-menu--horizontal) {
    .el-menu-item {
      font-size: 16px;
      height: 50px;
      line-height: 50px;

      &.is-active {
        font-weight: 600;
        @apply text-primary-500 dark:text-primary-400;
      }
    }
  }
}

.el-pagination {
  :deep(.el-pagination__total),
  :deep(.el-pagination__jump) {
    @apply dark:text-gray-400;
  }

  :deep(.el-input__inner) {
    @apply dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600;
  }
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.service-dialog {
  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__header {
    padding: 16px;
    background-color: #f0f0f0;
    border-bottom: 1px solid #e0e0e0;
  }

  .el-dialog__title {
    font-size: 18px;
    font-weight: 600;
  }

  .el-dialog__footer {
    padding: 16px;
    background-color: #f0f0f0;
    border-top: 1px solid #e0e0e0;
  }
}

.chat-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    overflow: hidden;
  }

  :deep(.el-dialog__header) {
    padding: 16px;
    margin: 0;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    @apply dark:bg-gray-800 dark:border-gray-700;
  }

  :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    @apply dark:text-gray-100;
  }

  :deep(.el-textarea__inner) {
    resize: none;
    @apply dark:bg-gray-800 dark:text-gray-100 dark:border-gray-700;
  }
}

.message-bubble {
  @apply rounded-lg p-3 shadow-sm;
  max-width: 100%;
  position: relative;

  &.message-received {
    border-radius: 0 12px 12px 12px;
    &::before {
      content: "";
      position: absolute;
      left: -6px;
      top: 0;
      border-style: solid;
      border-width: 0 8px 8px 0;
      border-color: transparent #fff transparent transparent;
      @apply dark:border-r-gray-700;
    }
  }

  &.message-sent {
    border-radius: 12px 0 12px 12px;
    &::before {
      content: "";
      position: absolute;
      right: -6px;
      top: 0;
      border-style: solid;
      border-width: 8px 8px 0 0;
      border-color: var(--el-color-primary) transparent transparent transparent;
    }
  }
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 2px;
  padding: 8px 12px;
  background: white;
  border-radius: 20px;
  @apply dark:bg-gray-700;

  span {
    width: 6px;
    height: 6px;
    background: #90959a;
    border-radius: 50%;
    animation: typing 1s infinite;
    @apply dark:bg-gray-400;

    &:nth-child(1) {
      animation-delay: 0s;
    }
    &:nth-child(2) {
      animation-delay: 0.2s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

@keyframes typing {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}

// 购物车样式
.cart-drawer {
  .cart-item {
    .item-image {
      img {
        @apply transition-transform duration-300;
      }

      &:hover img {
        @apply scale-110;
      }
    }

    .item-name {
      &:hover {
        @apply cursor-pointer;
      }
    }

    .el-input-number {
      @apply w-24;
    }
  }

  .empty-cart {
    .el-icon {
      @apply opacity-50;
    }
  }

  .cart-footer {
    .checkout-button {
      @apply rounded-lg;
    }
  }
}

// 收藏夹样式
.favorites-drawer {
  .favorite-items {
    @apply space-y-4;

    .favorite-item {
      @apply flex items-start gap-4 p-4 bg-gray-50 rounded-lg;

      .item-image {
        @apply w-24 h-24 rounded-lg overflow-hidden flex-shrink-0;

        :deep(.el-image) {
          @apply w-full h-full object-cover;
        }
      }

      .item-info {
        @apply flex-1;

        .item-name {
          @apply font-medium text-gray-900 mb-2 line-clamp-2;
        }

        .item-price {
          @apply text-lg font-bold text-primary-600;
        }
      }

      .item-actions {
        @apply flex flex-col gap-2;
      }
    }
  }
}

// 自定义工具栏 tooltip 动画
:deep(.toolbar-tooltip) {
  .el-popper {
    transition:
      opacity 0.15s,
      transform 0.15s !important;
  }

  &.is-hidden {
    opacity: 0;
    transform: scaleY(0.9);
    transition:
      opacity 0.1s,
      transform 0.1s !important;
  }
}
</style>
